package com.zzty.txj1.controller;


import com.zzty.txj1.config.WeiChatConfig;
import com.zzty.txj1.util.MessageHandlerUtil;
import com.zzty.txj1.util.MessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@RestController
@RequestMapping("/wechat")
public class WeChatController {
    private static final Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Value("${wechat.token}")
    private String TOKEN;
    String url1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiChatConfig.appid + "&redirect_uri=";           //String url2="&redirect_uri=";
    String url2 = "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";


    @RequestMapping("/init")
    public void init(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("wechat--controller ============ init");

        logger.info("wechat--controller ============ 开始校验签名");
        /**
         * 接收微信服务器发送请求时传递过来的4个参数
         */
        String signature = request.getParameter("signature");//微信加密签名signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String timestamp = request.getParameter("timestamp");//时间戳
        String nonce = request.getParameter("nonce");//随机数
        String echostr = request.getParameter("echostr");//随机字符串
        //排序
        String sortString = sort(TOKEN, timestamp, nonce);
        //加密
        String mySignature = sha1(sortString);
        //校验签名
        if (mySignature != null && mySignature != "" && mySignature.equals(signature)) {
            logger.info("wechat--controller ============ 签名校验通过。");
            //如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
            //response.getWriter().println(echostr);
            response.getWriter().write(echostr);
        } else {
            logger.info("wechat--controller ============ 签名校验失败.");
        }
    }

    /**
     * 排序方法
     *
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    public String sort(String token, String timestamp, String nonce) {
        logger.info("wechat--controller ============ sort");

        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);
        StringBuilder sb = new StringBuilder();
        for (String str : strArray) {
            sb.append(str);
        }

        return sb.toString();
    }

    /**
     * 将字符串进行sha1加密
     *
     * @param str 需要加密的字符串
     * @return 加密后的内容
     */


    public String sha1(String str) {
        logger.info("location--controller ============ add");

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    @RequestMapping(value = "/init", method = RequestMethod.POST)
    public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("location--controller ============ add");

        // TODO 接收、处理、响应由微信服务器转发的用户发送给公众帐号的消息
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        System.out.println("请求进入");

        String responseMessage = "";
        try {
            //解析微信发来的请求,将解析后的结果封装成Map返回
            Map<String, String> map = MessageHandlerUtil.parseXml(request);
            logger.info("wechat--controller ============ 开始构造响应消息");
            String msgType = map.get("MsgType").toString();
            if (MessageType.EVENT.equals(msgType) && "subscribe".equals(map.get("Event").toString())) {
                responseMessage = MessageHandlerUtil.buildResponseMessage(map);
                response.getWriter().println(responseMessage);
            }


        } catch (Exception e) {
            e.printStackTrace();
            logger.info("wechat--controller ============ 发生异常：" + e.getMessage());
            //responseMessage ="未正确响应";
        }
        //发送响应消息


    }
}

